<?php

namespace App\Http\Controllers\Business;

use App\Http\Util\Tool;
use App\Model\Menus;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class MenusController extends Controller
{


    /**获取菜单栏
     * @return \Illuminate\Http\JsonResponse
     */

    public function getMenus()
    {
        $data = Menus::where('pid', 0)
            ->where('is_del', 1)
            ->where('status', 1)
            ->orderBy('sort', 'desc')
            ->get(['id', 'name', 'pid', 'url', 'icon', 'component', 'status', 'label', 'sort'])
            ->toArray();
        $data = Tool::getChild($data);
        return response()->json(['code' => 200, 'msg' => 'ok', 'data' => $data]);
    }


    /**创建编辑菜单
     * @return \Illuminate\Http\JsonResponse
     */
    public function createMenus()
    {
        try {
            $data = request()->post();
            if (!array_key_exists('id', $data) || $data['id'] <= 0) {
                Menus::create($data);
            } else {
                if (array_key_exists('children', $data)) {
                    unset($data['children']);
                }
                Menus::where('id', $data['id'])->update($data);
            }
            return response()->json(['code' => 200, 'msg' => '操作成功', 'data' => $data]);
        } catch (\Exception $e) {
            return response()->json(['code' => 1001, 'msg' => '操作繁忙 请稍后再试']);
        }

    }

    /**删除菜单
     * @return \Illuminate\Http\JsonResponse
     */
    public function delMenus()
    {
        try {
            $id = request()->get('id');
            $child = Menus::where('pid', $id)
                ->where('is_del', 1)
                ->count();
            if ($child > 0) {
                return response()->json(['code' => 1001, 'msg' => '请先删除子菜单']);
            }
            $model = Menus::find($id);
            $model->is_del = 0;
            if ($model->save()) {
                return response()->json(['code' => 200, 'msg' => '删除成功']);
            }
        } catch (\Exception $e) {
            return response()->json(['code' => 1001, 'msg' => '操作繁忙 请稍后再试']);
        }
    }


}
